<script setup lang='ts'>
import { SiderMenuEnum } from '@/models/@types';
import { appRef } from '@/models/app.ref';
import Explanation from '@/components/Explanation.vue'
import { onMounted, ref } from 'vue';
import { AIDrawMenuInfo } from '@/models/aidraw';
import { drawService } from '@/services/aidraw.service';
import DrawSpeciality from '@/components/chat/DrawSpeciality.vue'
import { AssetInfo } from '@/models/asset';
import { mediaService } from '@/services/media.service';
import { hope } from '@/tools/hope/@types/hope';

const menus = ref([]);
const currMenu = ref({} as AIDrawMenuInfo);
const image = ref({} as AssetInfo)
const loading = ref(false);


onMounted(() => {
  init();
  getModel();
  mediaService.all(1, 100);
})

async function getModel(): Promise<void> {
  loading.value = true;
  await drawService.getModels();
  loading.value = false;
}

async function init(): Promise<void> {
  menus.value = await appRef.aidraw.menus();
  currMenu.value = appRef.aidraw?.currMenu;
  // console.log(menus.value);
  image.value = {} as AssetInfo;
  if (currMenu.value?.image?.task_id) getImage();
}

async function onAdd(e: { type: SiderMenuEnum, parent?: string }): Promise<void> {
  const { type, parent } = e
  await appRef.aidraw.add(type, parent);
  init();
}
async function onUpdate(enmus: AIDrawMenuInfo[]): Promise<void> {
  await appRef.aidraw.update(enmus)
  init();
}
async function onItem(uid: string): Promise<void> {
  console.log('onItem', uid);
  await appRef.aidraw.setCurrKey(uid);
  init();
}
async function onEdit(param: { uid: string, label: string }): Promise<void> {
  const { uid, label } = param;
  await appRef.aidraw.edit(uid, label);
}

async function getImage(): Promise<void> {
  const { img } = currMenu.value.image;
  image.value = img;
}


const isSend = ref(false);
async function onDraw(value: { prompt: string; negative_prompt: string; width: number; height: number; ratio: string; step: number; picture_weight: number; original: AssetInfo, model_name: string }): Promise<void> {
  if (!appRef.aidraw.models?.length) {
    await getModel();
  }
  isSend.value = true;
  scrollTopBottom();
  drawService.generateV2(value).then(() => {
    isSend.value = false;
    onLoad();
  }).catch(() => {
    isSend.value = false;
    isLoad.value = false;
  });
}

const isLoad = ref(false);
function onLoad(): void {
  isLoad.value = true;
  const { forward, exclude, model, picture_weight, width, height, step, ratio, original, task_id } = currMenu.value.image;
  drawService.checkTaskStatus(task_id).then(async (res) => {
    await appRef.aidraw.updateImage(task_id, res, forward, exclude, model, picture_weight, ratio, original, width, height, step)
    getImage();
    isLoad.value = false;
  }).catch(async () => {

    await appRef.aidraw.updateImage('', {} as AssetInfo, forward, exclude, model, picture_weight, ratio, original, width, height, step);
    isLoad.value = false;
  })
}
/** 自动滚动到底部 */
const mainRef = ref(null)
const oldScollTop = ref(0);

function scrollTopBottom() {
  const { scrollHeight, clientHeight } = mainRef.value;
  mainRef.value.scrollTop = scrollHeight - clientHeight;
  oldScollTop.value = mainRef.value.scrollTop;
}

const shareLoading = ref(false);
function onShare(): void {
  if (shareLoading.value) true;
  if (appRef.user?.data?.uid) {
    shareLoading.value = true;
    const { forward, exclude, img } = currMenu.value.image;
    mediaService.add(img.id, forward, exclude).then(() => {
      shareLoading.value = false;
      init();
    })
  } else {
    hope.login();
  }
}

</script>
<template>
  <div class="index">
    <a-layout style="height: 100%;">

      <a-layout>
        <div class="main flex scrollbar-none" v-if="currMenu?.uid" ref="mainRef">
          <DrawSpeciality :info="currMenu.image" :is-draw="isSend" @draw="onDraw" />
          <div class="content  ">

            <a-spin :loading="isSend || isLoad" v-if="image?.id || isSend || isLoad"
              style="width: 100%;height: 100%;position: relative;">
              <template #tip>
                <p style="margin-bottom: 10px;">{{ isLoad ? '获取图片中' : '图片绘制中' }}</p>
                <a-button size="mini" v-if="isLoad" @click="isLoad = false">关闭加载</a-button>
              </template>
              <a-image fit="contain" width="100%" height="100%" class="image" v-if="image" :src="image.snapshot">
                <template #loader>
                  <icon-loading />
                </template>
              </a-image>
              <a-button class="load" type="primary" @click.stop="onLoad"
                v-if="!image && currMenu.image?.task_id && !isLoad">
                加载图片
              </a-button>
              <div class="share" v-if="!currMenu.image?.isShare" @click="onShare">
                <div class="title flex">
                  <a-spin v-if="shareLoading" :size="20" />
                  <icon-share-alt size="20" style="margin-right: 6px;" v-else />
                  分享至画廊
                </div>
                <div class="desc"> 审核后将公开展示至画廊 </div>
              </div>
            </a-spin>
            <Guide v-else></Guide>
          </div>
        </div>
        <Explanation v-else />
      </a-layout>
      <Sider :menus="menus" :default-uid="currMenu?.uid" @add="onAdd"
        @clear="async () => { await appRef.aidraw.clear(); init() }" @click-item="onItem"
        @edit="($event) => { onEdit($event); init() }"
        @remove="async ($event) => { await appRef.aidraw.remove($event); init() }"
        @update="($event) => onUpdate($event)" />
    </a-layout>
  </div>
</template>
<style lang='scss' scoped>
.index {
  height: 100%;

  .main {
    width: 95%;
    max-width: 1270px;
    margin: 0 auto;
    padding: 20px 0;
    overflow-y: auto;
    position: relative;
    scroll-behavior: smooth;

    .content {
      padding: 20px;
      width: 100%;
      height: 100%;
      flex: 1;
      overflow: hidden;
      // background: var(--color-neutral-2);
      border: 1px solid var(--color-neutral-4);
      position: relative;

      .share {
        position: absolute;
        bottom: 10px;
        left: 50%;
        transform: translateX(-50%);
        cursor: pointer;
        padding: 0.875rem;
        border: 1px solid var(--color-neutral-2);
        border-radius: 8px;
        transition: all .3s;
        background: var(--color-bg-1);

        &:hover {
          border-color: var(--color-neutral-4);
          color: rgb(var(--arcoblue-5));
        }

        .title {
          font-size: 14px;
          font-weight: 600;
        }

        .desc {
          font-size: 10px;
          margin-top: 6px;
          color: var(--color-neutral-7);
        }
      }

      .image {
        max-width: 100%;
        max-height: 100%;
      }

      .load {
        position: absolute;
        top: 55%;
        left: 50%;
        transform: translate(-50%, -50%);
      }
    }

    .prompt {
      width: 100%;
      margin-bottom: 10px;
      justify-content: flex-end;
      align-items: flex-end;

      .left {
        .item {
          margin: 0;
          margin-right: 5px;

          &:last-child {
            margin: 0;
          }
        }
      }

      .right {
        margin-left: 10px;
        align-items: flex-end;

        .item {
          background: rgb(var(--primary-5));
          border-radius: 20px 20px 0 20px;
          height: 37px;
          margin-right: 5px;
          cursor: pointer;
          width: fit-content;
        }
      }
    }

    .bottom {
      width: 100%;
      position: relative;

      .textarea {
        height: 170px;
        margin-right: 10px;

        &:last-child {
          margin: 0;
        }
      }
    }

    @media screen and (max-width: 1200px) {
      flex-flow: column;

      .prompt {
        justify-content: space-between;
      }

      .content {
        flex: none;
      }

      .bottom {
        flex-direction: column;

        .textarea {
          height: 130px;
          width: 100%;
          margin-right: 0;
          margin-bottom: 10px;
        }
      }
    }
  }
}
</style>
